﻿using System;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Net;
using System.Windows;

namespace TemperatureWP.ViewModel
{
    public class ExtendedViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public App ThisApp;

        public ExtendedViewModelBase()
        {
            ThisApp = Application.Current as App;
        }

        public void ReceiveData(string uri, DownloadStringCompletedEventHandler receiveDataHandler)
        {
            // Source : http://developer.nokia.com/Community/Wiki/Employees_app_with_XML_parsing_and_messaging_in_WP
            // Is network connection available
            if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            {
                MessageBox.Show("No network connection available!");
                return;
            }

            var webClient = new WebClient();
            webClient.DownloadStringCompleted += receiveDataHandler;
            webClient.DownloadStringAsync(new Uri(uri));
        }

        public void SendData(string uri, UploadStringCompletedEventHandler sendDataHandler = null)
        {
            // Source : http://developer.nokia.com/Community/Wiki/Employees_app_with_XML_parsing_and_messaging_in_WP
            // Is network connection available
            if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            {
                MessageBox.Show("No network connection available!");
                return;
            }

            var webClient = new WebClient();
            webClient.UploadStringAsync(new Uri(uri), "POST");
            if (sendDataHandler != null)
                webClient.UploadStringCompleted += sendDataHandler;
        }

        public void Navigate(Type destination)
        {
            var uri = destination.Name == typeof(MainPage).Name 
                ? "/../MainPage.xaml" 
                : string.Format("/Views/{0}.xaml", destination.Name);

            ThisApp.RootFrame.Navigate(new Uri(uri, UriKind.RelativeOrAbsolute));
        }

        public void NotifyPropertyChanged<T>(object sender, Expression<Func<T>> property)
        {
            // Source: http://stackoverflow.com/questions/3269518/get-the-property-name-used-in-a-lambda-expression-in-net-3-5/3269544#3269544
            var body = property.Body as MemberExpression;
            if (PropertyChanged != null && body != null)
                PropertyChanged(sender, new PropertyChangedEventArgs(body.Member.Name));
        }
    }
}
